package com.bzframework.core.doc.manager;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bzframework.core.doc.InformationSchemaColumnEntity;
import com.bzframework.core.doc.InformationSchemaTableEntity;
import com.bzframework.core.doc.service.column.InformationSchemaColumnService;
import com.bzframework.core.doc.service.table.InformationSchemaTableService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.TableRenderData;
import com.deepoove.poi.data.Tables;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author bingzhong
 * @Date 2025/7/10
 */
@Component
@RequiredArgsConstructor
public class DefaultGenerateTableDocManager implements GenerateTableDocManager {

    private final InformationSchemaColumnService informationSchemaColumnService;

    private final InformationSchemaTableService informationSchemaTableService;

    @Override
    @SneakyThrows
    public void generateTableDoc(String schema) {

        List<InformationSchemaColumnEntity> schemaColumnEntities = informationSchemaColumnService.list(
                Wrappers.<InformationSchemaColumnEntity>lambdaQuery()
                        .eq(InformationSchemaColumnEntity::getTableSchema, schema)
        );

        Map<String, List<InformationSchemaColumnEntity>> columnMap = schemaColumnEntities
                .stream()
                .collect(Collectors.groupingBy(InformationSchemaColumnEntity::getTableName));

        Set<String> tableNameSet = columnMap.keySet();

        List<InformationSchemaTableEntity> schemaTableEntities = informationSchemaTableService.list(
                Wrappers.<InformationSchemaTableEntity>lambdaQuery()
                        .eq(InformationSchemaTableEntity::getTableSchema, schema)
                        .in(InformationSchemaTableEntity::getTableName, tableNameSet)
        );

        Map<String, String> tableMap = schemaTableEntities
                .stream()
                .collect(Collectors.toMap(InformationSchemaTableEntity::getTableName, InformationSchemaTableEntity::getTableComment));

        RowRenderData topRenderData = Rows.of("字段名", "字段类型", "注释", "是否必填")
                                          .center()
                                          .create();

        Configure configure = Configure.builder()
                                       .useSpringEL()
                                       .build();

        List<InformationSchemaTableEntity> dataList = new ArrayList<>();
        columnMap.forEach((key, value) -> {

            List<RowRenderData> rowRenderDataList = new ArrayList<>();
            rowRenderDataList.add(topRenderData);
            for (InformationSchemaColumnEntity schemaColumnEntity : schemaColumnEntities) {
                RowRenderData rowRenderData = Rows
                        .of(schemaColumnEntity.getColumnName(), schemaColumnEntity.getColumnType(), schemaColumnEntity.getColumnComment(),
                            schemaColumnEntity.getIsNullable().equals("YES") ? "否" : "是")
                        .center()
                        .create();
                rowRenderDataList.add(rowRenderData);
            }

            TableRenderData tableRenderData = Tables.create(rowRenderDataList.toArray(new RowRenderData[0]));
            dataList.add(InformationSchemaTableEntity.builder()
                                                     .tableName(key)
                                                     .tableComment(tableMap.get(key))
                                                     .tableRenderData(tableRenderData)
                                                     .build());
        });

        // 渲染数据区块对
        Map<String, Object> map = new HashMap<>();
        map.put("tableList", dataList);
        ClassPathResource tableTemplateResource = new ClassPathResource("document/table_template.docx");
        if (!tableTemplateResource.exists()) {
            throw new RuntimeException("找不到模板文件");
        }
        String tableTemplateStr = "./data/document";
        Path tableTemplatePath = Paths.get(tableTemplateStr);
        if (!Files.exists(tableTemplatePath)) {
            Files.createDirectories(tableTemplatePath);
        }
        String fullFilePath = String.format("%s/%s_%s.docx", tableTemplateStr, "table_template", System.currentTimeMillis());
        XWPFTemplate template = XWPFTemplate.compile(tableTemplateResource.getInputStream(), configure).render(map);
        template.writeToFile(fullFilePath);
        template.close();

    }
}
